package com.ooqiu.gaming.components.retrofit.convert;

import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.ooqiu.gaming.api.base.BaseResponse;
import com.ooqiu.gaming.ui.login.LoginActivity;

import java.io.IOException;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;
import retrofit2.Converter;

/**
 * @author baronzhang (baron[dot]zhanglei[at]gmail[dot]com)
 *         16/2/25
 */
final class FastJsonResponseBodyConvert<T> implements Converter<ResponseBody, T> {

    private Type type;

    public FastJsonResponseBodyConvert(Type type) {
        this.type = type;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        String body = value.string();
        BaseResponse response = JSON.parseObject(body, BaseResponse.class);
//        LogUtil.json(body);
        if (response.isSuccess()) {
            return JSON.parseObject(body, type);
        } else {
//            throw new IllegalStateException(String.format("code = %s; msg = %s", response.getCode(), response.getMsg()));
            if (response.getCode() == 2) {
                ARouter.getInstance().build(LoginActivity.PATH)
                        .navigation();
                throw new IllegalStateException("登录信息失效,请重新登录");
            } else {
                throw new IllegalStateException(response.getMsg());
            }


        }
    }
}
